<script setup>
import { useUserStore  } from '../stores/user'
import {ref,reactive,computed} from 'vue'
import getArticle from '../api/getArticle.js'
import article from '../api/getArticleById';
import { useRouter } from 'vue-router';
import images from '../components/imageShow.vue';
import isAdmin from '../api/isAdmin.js'
import { Setting,CircleCloseFilled,Plus } from '@element-plus/icons-vue'
import updateArticle from '../api/updateArticle.js'
import updateArticleAdmin from '../api/updateArticleAdmin'
import updateUser from "../api/updateUser.js"
import sender from '../api/sendConfirmCode.js'
import imageShow from '../components/imageShow.vue';
const userId = ref(localStorage.getItem("userId"))
const use = useRouter() ;
const isSet = ref(false)
const loading = ref(false)
const noMore = ref(false)
const disabled = computed(() => loading.value || noMore.value)
const imageUrl = ref("")
const image_id = ref("")
const userInform = useUserStore()
const Articles = ref([])
const pagesize = ref(10)
let type = ref(userInform.types[0])
let pageNum = 0
const flagForSearch = ref(false)

isAdmin().then((res)=>{
  if(res.status == 200)
  {
    isSet.value = true
    an_state.value = true
  }
})

function getArticleType(value)
{
    if(type.value != value) {
    type.value = value
    pageNum = 0 ;
    Articles.value =[]
    }

    getArticle({
        type: value,
        page: pageNum++,
        size: pagesize.value
    }).then(function(response){
        if(response.data == "" || response.data==undefined)
        {
          noMore.value = true ; 
        }
        else if(response.status == 200)
        {        
            response.data.forEach(element => {
            Articles.value.push(element);
          });
        noMore.value  = false}
        if (Articles.value.length == 0) {
        flagForSearch.value = true ; 
        }
    })
    
}
const load = () => {
    loading.value = true
    setTimeout(() => {  
    loading.value = false
    console.log(1)
    getArticleType(type.value)
    }, 1000)
    
}
getArticleType(type.value)

function ToArticle(param){
  use.push("/article?param="+param)
}
const disposeUser = ref({})
const visible = ref(false)
const dispose= ref({})
const disposeFlag = ref(false)
const oldUser = ref({})
const an_state = ref(false)
const url = "http://localhost:5173/api/image/upload?token=Bearer " + localStorage.getItem("jwttoken")

function timerHandler () {
            setInterval(()=>{timeOut.value--},1000)
        }

function funcArticle(id){
    use.push("/article?param="+id)
}
  //判断是否登录 并获得chatlist 

function AdminSet(item){
    visible.value = true
    dispose.value = item
}

function getUserByLink(userId){
    
    getUserEntity(userId).then((res)=>{
        if(res.status == 200)
        {
            disposeUser.value = res.data
            oldUser.value = res.data
            console.log(res.data)
            disposeFlag.value = true
        }
    })
}

function updateUserByDraw(user){
    updateUser(user,confirm_code.value).then((res)=>{
        if(res.status == 200)
        {
            console.log(res)
        }
    })
}

function updateArticleByDraw(){
    if(an_state.value)
    {
      console.log(dispose.value)
        updateArticleAdmin({
          id:dispose.value.id,
          state:dispose.value.state
        }).then((res)=>{
            if(res.status == 200)
            {
                dispose.value = res.data
                ElMessage.success("修改成功")
            }
        })
    }
    else {
        console.log(dispose.value)
        updateArticle({
          id:dispose.value.id,
          author:dispose.value.author,
          content:dispose.value.content,
          state:dispose.value.state,
          imageId:dispose.value.imageId == null ? ""  : (dispose.value.imageId),
          images:dispose.value.images == null ?  "" : (dispose.value.images),
          title:dispose.value.title,
          type:dispose.value.type,
          userId:dispose.value.userId
        }).then((res)=>{
            if(res.status == 200)
            {
                dispose.value = res.data
                ElMessage.success("修改成功")
            }
        })
    }
}

function sendConfirmCode(){
        if(oldUser.value.email.trim === "" || oldUser.value.email == undefined || oldUser.value.email === "")
        {
            ElMessage({message:'请输入邮箱',
            type:"error"})
            return null
            }
            timeOut.value = 180
            timerHandler()
            sender(oldUser.value.email).then(
            (res)=>{
            if( res.status == "200" ){
            }
            }
            )
        }
    function successHandler (res,file){ 
        image_id.value =res
        imageUrl.value = URL.createObjectURL(file.raw);
        dispose.value.imageId = image_id.value
    }
    function beforeAvatarUpload(file) {
        const isJPG = (file.type === 'image/jpeg' || file.type === 'image/png');
        const isLt2M = file.size / 1024 / 1024 < 2;

        if (!isJPG) {
          ElMessage.error('上传头像图片只能是 JPG / PNG 格式!');
        }
        if (!isLt2M) {
          ElMessage.error('上传头像图片大小不能超过 2MB!');
        }


        return isJPG && isLt2M;
      }



</script>

<template>
    <el-menu :default-active="activeIndex"
    class="el-menu-demo"
    mode="horizontal"
    @select="handleSelect"
    style="height: 4rem; width: 83vw; ">
        <el-menu-item style="width: 8vw;" v-for="(item, index) in userInform.types" :key="index" @Click="getArticleType(userInform.types[index])" >
            {{ item }}
        </el-menu-item>
    </el-menu>
    
    <div style="position: relative;">
    <div class="article-box" style="overflow: auto">
      <div v-if="flagForSearch">
        <el-empty description="description" />
      </div>
    <ul v-infinite-scroll="load" infinite-scroll-distance="10" :infinite-scroll-disabled="disabled" v-else="flagForSearch">
      <li v-for="(item,index) in Articles" :key="index" class="display-item" >
        <el-card shadow="hover" class="card-box"> 
                <div style="width: 100px;" @click="ToArticle(item.id)"><images class="image-box" :value="item.imageId"></images></div>
                <nav class="content-box">
                <div class="title" @click="ToArticle(item.id)">
                  <el-popover
                    placement="right" :width="400"
                    trigger="hover"
                  >
                    <template #reference>
                      {{ item.title }}
                    </template>
                    <div v-html="item.content.substring(0,60)">
                    </div>
                  </el-popover>
                  </div>
                <div class="author">发布者： <el-link @click="use.push('/selfInform?userId='+item.userId)" >{{ item.userId }}</el-link> &nbsp;&nbsp;&nbsp; <br>作者：{{ item.author }}</div>
                <div class="type"><el-tag size="small">{{ item.type }}</el-tag></div>
                <div><el-text size="small"> 日期:{{ item.authorCreatedTime }}</el-text> &nbsp; 访问量：{{ item.visits }} </div>
                </nav>
                <div class="btn-box" v-show="item.userId == userId || isSet"> <el-button :icon="Setting" @Click="AdminSet(item)" circle> </el-button> </div>
            </el-card>
      </li>
      </ul>
      <p v-if="loading">Loading...</p>
      <p v-if="noMore">已经到底了</p>
    </div>
    </div>
    <el-drawer v-model="visible" :show-close="false">
    <template #header="{ close, titleId, titleClass }">
        <h4 :id="titleId" :class="titleClass">{{ dispose.title }}</h4>
        <el-button type="danger" @click="close">
        <el-icon class="el-icon--left"><CircleCloseFilled /></el-icon>
        Close
        </el-button>
    </template>
    <div>发布者：<el-link @click="getUserByLink(dispose.userId)">{{ dispose.userId }}</el-link>&nbsp;&nbsp;&nbsp;编号：<el-link @click="use.push('/article?param='+dispose.id)">{{ dispose.id }}</el-link></div>
    <br>
    <div>类型：<el-input v-model="dispose.type"/></div>
    <br>
    <div>作者：<el-input v-model="dispose.author"/></div>
    <br>
    <div>发布日期：{{dispose.authorCreatedTime}} </div>
    <br>
    <div>
        封面：<br>
            <imageShow style="width: 160px; height: 160px;" :value="dispose.imageId"></imageShow>
        <el-upload
        class="avatar-uploader"
        :action="url"
        :show-file-list="true"
        :on-success = "successHandler"
        :before-upload="beforeAvatarUpload">
        
        <img v-if="imageUrl != ''" :src="imageUrl" class="avatar">
        <el-icon v-else class="el-icon-plus avatar-uploader-icon"> <Plus></Plus> </el-icon>
        </el-upload>
    </div>
    <br>
    内容：<br>
    <div v-html=" dispose.content " class="dispose-box"></div>
    <br>
    <div v-if="dispose.state || isSet" >状态：<el-switch v-model="dispose.state"/></div>
    <div v-else>状态：<el-switch v-model="dispose.state" disabled/></div>
    <br>
    <div>
        <el-button @click="updateArticleByDraw()" text>
            提交  
        </el-button>
    </div>
    
    
    <el-drawer
        v-model="disposeFlag"
        :append-to-body="true"
        :before-close="handleClose"
        >
            <div> 用户名： {{disposeUser.username}} &nbsp;&nbsp;&nbsp;权限: {{ disposeUser.role.slice(5) }} </div>
            <br>
            <div> 生日： <el-date-picker v-model="disposeUser.birthDate" type="date" /></div>
            <br>
            <div>邮箱 : <el-input v-model="disposeUser.email"/><el-button v-show="timeOut<=0" text @click="sendConfirmCode">发送</el-button></div>
            <div>验证码：<el-input v-model="confirm_code" style="width: 80px;"/> <span v-show="timeOut>0" style="margin-left:4%; color : #999" >有效时间:{{ timeOut }}</span></div>
            <br>
            <div> 全名：<el-input v-model="disposeUser.fullName"/> </div>
            <br>
            <div>地址：<el-input v-model="disposeUser.address"/></div>
            <br>
            <div><el-button text @click="updateUserByDraw(disposeUser)">   提交  </el-button></div>
    </el-drawer>

    </el-drawer>
</template>

<style>
@import "../css/userinform.css"
</style>